/*
 * Copyright 2010 Mark Southern, The Scripps Research Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.exceltablemodel;

import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Workbook;

/*
 * @author Mark Southern (southermark at gmail dot com)
 */
public class ExcelImageUtils {

	private int padding = 2;

	public int getPadding() {
		return padding;
	}

	public void setPadding(int padding) {
		this.padding = padding;
	}

	protected void setWidthAndHeight(Cell cell, int imageWidthPx, int imageHeightPx) {
		short width = ConvertImageUnits.pixel2WidthUnits(imageWidthPx + 2 * padding);
		float height = ConvertImageUnits.pixelsToPoints(imageHeightPx + 2 * padding);
		// todo: check that the image size is less than excel's max allowed and adjust appropriately.
		cell.getSheet().setColumnWidth(cell.getColumnIndex(), width);
		cell.getRow().setHeightInPoints(height);
	}

	public void insertCellImage(Cell cell, Drawing drawing, byte[] imageData, int pictureType, int imageWidthPx, int imageHeightPx) throws IOException {
		setWidthAndHeight(cell, imageWidthPx, imageHeightPx);
		insertImage(cell, drawing, imageData, pictureType);
	}

	public void insertCellImage(Cell cell, Drawing drawing, URL url, int imageWidthPx, int imageHeightPx) throws IOException {
		insertCellImage(cell, drawing, toByteArray(url.openStream()), getPictureType(url), imageWidthPx, imageHeightPx);
	}
	
	public void insertCellImage(Cell cell, Drawing drawing, RenderedImage image) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(image, "png", baos);
		insertCellImage(cell, drawing, baos.toByteArray(), Workbook.PICTURE_TYPE_PNG, image.getWidth(), image.getHeight());
	}

	protected Picture insertImage(Cell cell, Drawing drawing, byte[] bytes, int pictureType) {
		Workbook workbook = cell.getSheet().getWorkbook();
		int row = cell.getRowIndex();
		int column = cell.getColumnIndex();
		ClientAnchor a = workbook.getCreationHelper().createClientAnchor();
		a.setAnchorType(ClientAnchor.MOVE_AND_RESIZE);
		a.setCol1(column);
		a.setCol2(column);
		a.setRow1(row);
		a.setRow2(row);
		a.setDx1(padding);
		a.setDy1(padding);
		a.setDx2(1023 - (2 * padding));
		a.setDy2(255 - (2 * padding));
		int index = workbook.addPicture(bytes, pictureType);
		Picture picture = drawing.createPicture(a, index);
		picture.getPreferredSize().setAnchorType(ClientAnchor.MOVE_AND_RESIZE);
		return picture;
	}

	protected Picture insertImage(Cell cell, Drawing drawing, URL url) throws IOException {
		return insertImage(cell, drawing, toByteArray(url.openStream()), getPictureType(url));
	}

	protected int getPictureType(URL url) {
		String sURL = url.toString().toLowerCase();
		int type;
		if (sURL.endsWith(".png"))
			type = Workbook.PICTURE_TYPE_PNG;
		else if (sURL.endsWith("jpg") || sURL.endsWith(".jpeg"))
			type = Workbook.PICTURE_TYPE_JPEG;
		else if (sURL.endsWith(".dib") || sURL.endsWith(".bmp") || sURL.endsWith(".wbmp"))
			type = Workbook.PICTURE_TYPE_DIB;
		else if (sURL.endsWith(".emf"))
			type = Workbook.PICTURE_TYPE_EMF;
		else if (sURL.endsWith(".pic") || sURL.endsWith(".pict"))
			type = Workbook.PICTURE_TYPE_PICT;
		else if (sURL.endsWith(".wmf"))
			type = Workbook.PICTURE_TYPE_WMF;
		else
			throw new IllegalArgumentException("Invalid Image extension for file: " + url);
		return type;
	}

	protected byte[] toByteArray(InputStream stream) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int read = 0;
		while (read != -1) {
			read = stream.read(buffer);
			if (read > 0)
				baos.write(buffer, 0, read);
		}
		return baos.toByteArray();
	}
}